// stores/connectionStore.ts - ޥ��
import { create } from 'zustand';
import { connectionService } from '../services/connections';
import type { ConnectionDetail, CreateConnectionRequest, ApiResponse } from '../types/api';

interface ConnectionStore {
  // �
  connections: ConnectionDetail[];
  currentConnection: string | null;
  loading: boolean;
  error: string | null;

  // �\
  fetchConnections: () => Promise<void>;
  createConnection: (config: CreateConnectionRequest) => Promise<ApiResponse>;
  deleteConnection: (connection: string) => Promise<ApiResponse>;
  setCurrentConnection: (connection: string | null) => void;
  checkConnectionHealth: (connection: string) => Promise<ApiResponse>;
  reconnectConnection: (connection: string) => Promise<ApiResponse>;
  closeConnection: (connection: string) => Promise<ApiResponse>;
  setDefaultConnection: (connection: string) => Promise<ApiResponse>;
  clearError: () => void;
}

export const useConnectionStore = create<ConnectionStore>((set, get) => ({
  // ˶
  connections: [],
  currentConnection: localStorage.getItem('currentConnection'),
  loading: false,
  error: null,

  // ��ޥh
  fetchConnections: async () => {
    set({ loading: true, error: null });
    try {
      const response = await connectionService.listConnections();
      set({
        connections: response.connections || response.items || [],
        loading: false
      });
    } catch (error) {
      set({
        error: 'Failed to fetch connections',
        loading: false
      });
    }
  },

  // �ޥ
  createConnection: async (config: CreateConnectionRequest) => {
    set({ loading: true, error: null });
    try {
      const response = await connectionService.createConnection(config);
      // Ͱ��ޥh
      await get().fetchConnections();
      set({ loading: false });
      return response;
    } catch (error) {
      set({
        error: 'Failed to create connection',
        loading: false
      });
      throw error;
    }
  },

  //  dޥ
  deleteConnection: async (connection: string) => {
    set({ loading: true, error: null });
    try {
      const response = await connectionService.deleteConnection(connection);
      // �� d�/SMޥzSMޥ
      if (get().currentConnection === connection) {
        get().setCurrentConnection(null);
      }
      // Ͱ��ޥh
      await get().fetchConnections();
      set({ loading: false });
      return response;
    } catch (error) {
      set({
        error: 'Failed to delete connection',
        loading: false
      });
      throw error;
    }
  },

  // �nSMޥ
  setCurrentConnection: (connection: string | null) => {
    if (connection) {
      localStorage.setItem('currentConnection', connection);
    } else {
      localStorage.removeItem('currentConnection');
    }
    set({ currentConnection: connection });
  },

  // ��ޥe��
  checkConnectionHealth: async (connection: string) => {
    try {
      const response = await connectionService.checkConnectionHealth(connection);
      return response;
    } catch (error) {
      set({ error: 'Failed to check connection health' });
      throw error;
    }
  },

  // Ͱޥ
  reconnectConnection: async (connection: string) => {
    try {
      const response = await connectionService.reconnectConnection(connection);
      // Ͱ��ޥh
      await get().fetchConnections();
      return response;
    } catch (error) {
      set({ error: 'Failed to reconnect' });
      throw error;
    }
  },

  // s�ޥ
  closeConnection: async (connection: string) => {
    try {
      const response = await connectionService.closeConnection(connection);
      // ��s�/SMޥzSMޥ
      if (get().currentConnection === connection) {
        get().setCurrentConnection(null);
      }
      // Ͱ��ޥh
      await get().fetchConnections();
      return response;
    } catch (error) {
      set({ error: 'Failed to close connection' });
      throw error;
    }
  },

  // �nؤޥ
  setDefaultConnection: async (connection: string) => {
    try {
      const response = await connectionService.setDefaultConnection(connection);
      // Ͱ��ޥh
      await get().fetchConnections();
      return response;
    } catch (error) {
      set({ error: 'Failed to set default connection' });
      throw error;
    }
  },

  // d�
  clearError: () => set({ error: null }),
}));